package com.omenkk.juc.AQS;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockCompetitionDemo {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        // 线程1 - 先获取锁并睡眠
        Thread thread1 = new Thread(() -> {
            System.out.println("Thread-1 尝试获取锁");
            lock.lock();
            try {
                System.out.println("Thread-1 获取锁成功，开始睡眠");
                Thread.sleep(3000); // 持有锁3秒
                System.out.println("Thread-1 释放锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "Thread-1");

        // 线程2 - 稍后启动，会竞争锁失败
        Thread thread2 = new Thread(() -> {
            try {
                // 确保线程1先获取锁
                Thread.sleep(100);
                System.out.println("Thread-2 尝试获取锁");
                lock.lock();
                try {
                    System.out.println("Thread-2 获取锁成功");
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "Thread-2");

        thread1.start();
        thread2.start();
    }
}